package io.yunho.yunho.interview.two.java8.webflux.holedemo;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author: yunho
 * @date: 2021/5/12 17:07
 * @description:
 */
@RestController
@RequestMapping("/xiaoqi")
public class UserController {
    private final UserRepository userRepository;
    public UserController(UserRepository userRepository){
        this.userRepository = userRepository;
    }
    @GetMapping(value = "/")
    public Flux<User> getAll(){
        return userRepository.findAll();
    }
    @GetMapping(value = "/stream",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> streamGetAll(){
        return userRepository.findAll();
    }

    @PostMapping("/")
    public Mono<User> putUser(@RequestBody User user){
        //spring data jpa 中 新增和修改都是save，有id为修改，无id为新增
        //需要自行判断是否将ID置空
//        user.setId(null);
        return this.userRepository.save(user);
    }
    @DeleteMapping("/{id}")
    public Mono<ResponseEntity<Void>> deleteUser(@PathVariable String id){
        //deleteByID 没有返回值，不能判断是否正常删除
        return this.userRepository.findById(id)
                //当要操作数据，并返回一个mono 使用flatmap
                //如果不操作数据，只是做转换
                .flatMap(user->this.userRepository.delete(user)
                        .then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK))))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }
    @PutMapping("/")
    public Mono<ResponseEntity<User>> updateUser(@RequestBody User user){
//        return this.userRepository.save(user); //不直接这么写 是因为有可能由于前端逻辑问题导致id传错或未传，从而引起服务异常，而且不容易找问题
        return this.userRepository.findById(user.getId())
                .flatMap(user1 -> {
                    user1.setUsername(user.getUsername());
                    user1.setAge(user.getAge());
                    return this.userRepository.save(user1);
                })
                .map(u -> new ResponseEntity<User>(u, HttpStatus.OK))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @GetMapping("/{id}")
    public Mono<ResponseEntity<User>> findUser(@PathVariable String id){
//        return this.userRepository.save(user); //不直接这么写 是因为有可能由于前端逻辑问题导致id传错或未传，从而引起服务异常，而且不容易找问题
        return this.userRepository.findById(id)
                .map(u -> new ResponseEntity<User>(u, HttpStatus.OK))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @GetMapping("/age/{start}/{end}")
    public Flux<User> findUser(@PathVariable int start, @PathVariable int end){
//        return this.userRepository.save(user); //不直接这么写 是因为有可能由于前端逻辑问题导致id传错或未传，从而引起服务异常，而且不容易找问题
        return this.userRepository.findByAgeBetween(start,end);
    }

    @GetMapping(value = "/stream/age/{start}/{end}",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> findUserStram(@PathVariable int start, @PathVariable int end){
//        return this.userRepository.save(user); //不直接这么写 是因为有可能由于前端逻辑问题导致id传错或未传，从而引起服务异常，而且不容易找问题
        return this.userRepository.findByAgeBetween(start,end);
    }

    @GetMapping("/old")
    public Flux<User> findUserOld(){
//        return this.userRepository.save(user); //不直接这么写 是因为有可能由于前端逻辑问题导致id传错或未传，从而引起服务异常，而且不容易找问题
        return this.userRepository.userOld();
    }

    @GetMapping(value = "/stream/old",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> findUserOldStram(){
//        return this.userRepository.save(user); //不直接这么写 是因为有可能由于前端逻辑问题导致id传错或未传，从而引起服务异常，而且不容易找问题
        return this.userRepository.userOld();
    }
    @PostMapping("/login")
    public R login(@RequestBody User user){
        System.out.println(user.toString());
        user.setAge(22);
        user.setId("001001");
        user.setToken(UUID.randomUUID().toString());

        return R.ok(user);
    }

    @PostMapping("/reg")
    public R reg(@RequestParam("username") String username, @RequestParam("password") String password){
        System.out.println("username****"+username+"______"+"password****"+password);
//        user.setAge(22);
//        user.setId("001001");
        if("kk".equals(username)){
            return R.failed("非法用户名");
        }
        return R.ok();
    }
    @GetMapping("/banner")
    public R banner(){
        List<HomeBanner> list=new ArrayList();
        HomeBanner homeBanner = new HomeBanner();
        homeBanner.setId("1");
        homeBanner.setTitle("豪车");
        homeBanner.setLinkUrl("https://www2.autoimg.cn/zxpt/g24/M06/05/67/720x360_0_autohomecar__Chtk3WC6BOWAWDCMAAHBLG6V0S8930.jpg");
        homeBanner.setCreateTime(new Date());
        list.add(homeBanner);
        homeBanner = new HomeBanner();
        homeBanner.setId("2");
        homeBanner.setTitle("哈哈");
        homeBanner.setLinkUrl("https://img3.autoimg.cn/soudfs/g24/M05/12/10/720x360_0_autohomecar__Chtk3WC6SpuAYlIcAAToS0VjM4g986.png");
        homeBanner.setCreateTime(new Date());
        list.add(homeBanner);
        homeBanner = new HomeBanner();
        homeBanner.setId("3");
        homeBanner.setTitle("呵呵");
        homeBanner.setLinkUrl("https://img3.autoimg.cn/soudfs/g24/M07/DA/43/720x360_0_autohomecar__ChwFjmC6SwWAZ0w9AAK1d7DAXMc927.png");
        homeBanner.setCreateTime(new Date());
        list.add(homeBanner);
        list.stream().forEach(System.out::println);
        return R.ok(list);
    }

    @GetMapping("/goods/{id}")
    public R goods(@PathVariable("id") String id){
        HomeBanner homeBanner = new HomeBanner();
        homeBanner.setId(id);
        homeBanner.setTitle("豪车");
        homeBanner.setLinkUrl("https://www2.autoimg.cn/zxpt/g24/M06/05/67/720x360_0_autohomecar__Chtk3WC6BOWAWDCMAAHBLG6V0S8930.jpg");
        homeBanner.setCreateTime(new Date());
        homeBanner.setTime(new Date().getTime());
        return R.ok(homeBanner);
    }
    @GetMapping("/index")
    public String xiaoqi(){
        return "你好，世界，我是小七 666 777 888 999 !!!!!!";
    }
}
